package com.ruoyi.framework.websocket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * websocket 消息处理
 * 
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数1000
     */
    public static int socketMaxOnlineCount = 1000;

    private static Map<String, String> USERLIST = new ConcurrentHashMap<String, String>();

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception
    {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            // 添加用户
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            LOGGER.info("\n SESSIONid - {}", session.getId());
            WebSocketUsers.sendMessageToUserByText(session, "连接成功|"+session.getId());
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(session.getId());
        //移除用户列表
        WebSocketUsers.removeUserList(session);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            String sessionId = session.getId();
            LOGGER.info("\n 连接异常 - {}", sessionId);
            LOGGER.info("\n 异常信息 - {}", exception);
            LOGGER.info("\n 异常信息内容 - {}", exception.getMessage());
            // 移出用户
            WebSocketUsers.remove(sessionId);
            //移除用户列表
            WebSocketUsers.removeUserList(session);
            // 获取到信号量则需释放
            SemaphoreUtils.release(socketSemaphore);
            // 关闭连接
            session.close();
        }

    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        LOGGER.info("收到消息:" + message);
        LOGGER.info("SESSIONID:" + session.getId());

        Map<String, String> content = new ConcurrentHashMap<String, String>();

        JSONObject reqJson = JSONObject.parseObject(message);
        String userId = reqJson.getString("userId");
        String type = reqJson.getString("type");
        String checkUserId = reqJson.getString("checkUserId");

        try {

            switch (type) {
                case "0":
                    sendMesageToUser(session, "0", userId, userId, "成功", "");
                    break;
                case "1":
                    sendMesageTocheckUser(session, "1", userId, checkUserId, "监管员不在线，请电话联系", message);
                    break;
                case "2":
                    sendMesageTocheckUser(session, "2", userId, checkUserId, "执行员不在线，请电话联系", message);
                    break;
                case "3":
                    sendMesageTocheckUser(session, "3", userId, checkUserId, "执行员不在线，请电话联系", message);
                    break;
                case "9":
                    WebSocketUsers.sendMessageToUserByText(session, message);
                    break;
                default:
                    sendMesageToUser(session, "5", userId, userId, "类型不正确", "");
                    break;
            }
        }catch(Exception e){
            content.put("type","0");
            content.put("checkUserId","0");
            content.put("userId",userId);
            content.put("data","异常请联系管理员");
            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(content));
            LOGGER.info("消息异常:" + e.getMessage(),e);
        }
    }
    public void  sendMesageToUser(Session session,String type,String userId,String checkUserId,String message,String data){

        Map<String,String> content = new ConcurrentHashMap<String,String>();
        Session toSession = WebSocketUsers.getUserSession(userId);

        if(toSession == null){
            Session session1 = WebSocketUsers.getUserSession(checkUserId);
            if(session1 != null){
                content.put("type",type);
                content.put("checkUserId",checkUserId);
                content.put("userId",userId);
                content.put("data",message);
                WebSocketUsers.sendMessageToUserByText(session1, JSON.toJSONString(content));
            }
            else{
                WebSocketUsers.setUserSession(userId,session);

                content.put("type","4");
                content.put("checkUserId",checkUserId);
                content.put("userId",userId);
                content.put("data",message);
                WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(content));
            }


        }else {
            if(!toSession.getId().equals("0")){
                WebSocketUsers.sendMessageToUserByText(toSession, message);
            }else{
                WebSocketUsers.setUserSession(userId,session);

                content.put("type",type);
                content.put("checkUserId",checkUserId);
                content.put("userId",userId);
                content.put("data",message);
                WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(content));
            }
        }
    }


    public void  sendMesageTocheckUser(Session session,String type,String userId,String checkUserId,String message,String data){

        Map<String,String> content = new ConcurrentHashMap<String,String>();
        Session toSession = WebSocketUsers.getUserSession(checkUserId);
        if(toSession == null){

            //WebSocketUsers.setUserSession(userId,session);
            if(type.equals("1")){
                content.put("type","4");
                content.put("checkUserId",checkUserId);
                content.put("userId",userId);
                content.put("data",message);
                WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(content));
            }else{
                content.put("type","6");
                content.put("checkUserId",checkUserId);
                content.put("userId",userId);
                content.put("data",message);
                WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(content));
            }
        }else {
            WebSocketUsers.sendMessageToUserByText(toSession, data);
        }
    }
}
